package edu.zut.service.impl;

import edu.zut.pojo.Account;
import edu.zut.repository.AccountRepository;
import edu.zut.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
//@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountRepository accountRepository;

    /**
     * 转账操作
     * @Transactional : 声明当前在业务在一个事务环境之下运行    一般是标注在方法上，也可以在类上
     * timeout:设置超时时间  以s为单位  propagation：设置事务传播行为
     * isolation：设置隔离级别   readOnly:设置是否为只读模式  true：查询   false：增删改
     * rollbackFor： 设置哪些异常回滚  默认是所有异常
     * @param from    转出人
     * @param to      转入人
     * @param balance 转账金额
     */
    @Override
    @Transactional(timeout = 10,propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,readOnly = false,
            rollbackFor = {Exception.class})
    public void transfer(Integer from, Integer to, double balance) {
        Optional<Account> optional = accountRepository.findById(from);
        Account from_account = optional.get();
        if (from_account.getBalance() >= balance) {
            //设置转出  -
            from_account.setBalance(from_account.getBalance() - balance);
            //调用数据层实现转出
            accountRepository.save(from_account);
            //查询转入方的账户
            Optional<Account> optional1 = accountRepository.findById(to);
            //假设在转账过程中发生异常
//            int i = 1/0;

            Account to_account = optional1.get();
            //设置转入  +
            to_account.setBalance(to_account.getBalance() + balance);
            accountRepository.save(to_account);
        }else {
            //可以手动抛出异常
        }

    }
}
